// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

  // LIFE-CYCLE CALLBACKS:
  cannon: cc.Node = null
  cannonScript: cc.Component = null
  onLoad () {
    debugger
    this.cannon = cc.find('Canvas/炮塔')
    this.cannonScript = this.cannon.getComponent('CannonScipt')
  }

  start () {
    this.node.on('touchstart', this.onTouchStart, this)
    this.node.on('touchmove', this.onTouchMove, this)
    this.node.on('touchend', this.onTouchEnd, this)
    this.node.on('touchcancle', this.onTouchCancle, this)
  }
  onTouchStart (e: cc.Event.EventTouch) {
    
  }
  onTouchMove (e: cc.Event.EventTouch) {
    let parent: cc.Node = this.node.getParent()
    // 将世界坐标转换为相对于父节点的相对坐标
    let pos: cc.Vec2 = parent.convertToNodeSpaceAR(e.getLocation())
    
    // 计算该点所在的方位 (cos, sin)
    let direction: cc.Vec2 = pos.normalize()
    // cc.log(`x:${direction.x}`, `y:${direction.y}`)
    // 将手柄限制在圆盘之内
    let maxR = 100 * 0.8
    let r :number = cc.Vec2.distance(pos, cc.v2(0, 0)) // 计算实际距离到圆心的距离
    if (r > maxR) {
      pos.x = maxR * direction.x
      pos.y = maxR * direction.y
    }

    this.node.setPosition(pos)

    // 操纵目标小车
    let radia = pos.signAngle(cc.v2(1, 0)) // 求两个向量的夹角弧度值
    let angle = radia / Math.PI * 180
    this.cannon.angle = -angle

    // // 设置小车的方向
    this.cannonScript.direction = this.cannon.angle
  }
  onTouchEnd () {
    this.node.setPosition(cc.v3(0, 0, 0))
    this.cannonScript.direction = 0
  }
  onTouchCancle () {
    
  }
  // update (dt) {}
}
